<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use App\Models\Coupon;
use App\Models\CouponType;
use Exception;

class SyncGenerateCoupons implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $number;
    public $card_type;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($number, $card_type)
    {
        $this->number = $number;
        $this->card_type = $card_type;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if ($this->number == 0 || $this->number > 1000000) {
            Log::info('SyncGenerateCoupons job 输入不合法，job结束。');
            return 0;
        }

        $couponType = CouponType::where('code', $this->card_type)->first();
        if (!$couponType) {
            Log::info('SyncGenerateCoupons job 输入的card_type不存在，job结束。');
            return 0;
        }

        $batchNumber = date("ymd") . Str::random(4);
        Log::info("正在生成 " . $this->number . " 张优惠劵, 批次为 " . $batchNumber . " ...");

        $success = 0;
        $failed = 0;
        while (($success + $failed) < $this->number) {
            try {
                Coupon::create([
                    'code' => Str::random(8),
                    'batch_code' => $batchNumber,
                    'card_type' => $this->card_type,
                    'price' => $couponType->price
                ]);
                $success++;
            } catch (Exception $e) {
                $failed++;
                Log::info($e->getMessage());
            }
        }

        Log::info($this->number . " 张 ".$this->card_type. " 优惠劵生成成功。");
    }
}
